package com.financing.wap.service.impl;



import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dao.IAccountDao;
import com.financing.wap.dao.IActivitieGiftDao;
import com.financing.wap.dao.IAnswerDao;
import com.financing.wap.dto.AccountCorpDTO;
import com.financing.wap.dto.AccountDetailDTO;
import com.financing.wap.dto.ActivitesAnswerDTO;
import com.financing.wap.dto.ActivitesMoneyDTO;
import com.financing.wap.dto.ActivitieGiftDTO;
import com.financing.wap.service.IAnswerService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.RandomUtils;
import com.financing.wap.vo.ActiviesMoneyAnswerVo;



/**
 * @author lisu
 *
 */
@Service("answerService")
public class AnswerServiceImpl implements IAnswerService{

	Logger logger =  Logger.getLogger(getClass());

	@Autowired
	private IAnswerDao answerDao;

	@Autowired
	private IAccountDao accountDao;

	@Autowired
	private IActivitieGiftDao activitieGiftDaoImpl;

	@Override
	public List<ActivitesAnswerDTO> searchAnswerByParas(ActivitesAnswerDTO queryDto) {

		return answerDao.searchAnswerByParas(queryDto);
	}

	@Override
	public int updateAnswerBySessionId(ActivitesAnswerDTO dto) {

		return answerDao.updateAnswerBySessionId(dto);
	}

	@Override
	public int insertAnswer(ActivitesAnswerDTO dto) {

		return answerDao.insertAnswer(dto);
	}

	@Override
	public void updateAccountAndAnswer(String userId,String sessionId,Integer accountId, BigDecimal s) throws SQLException {
		logger.info("第一步：更新答案表");
		ActivitesAnswerDTO answerDto = new ActivitesAnswerDTO();
		answerDto.setuId(userId);
		answerDto.setSessionId(sessionId);
		answerDao.updateAnswerBySessionId(answerDto);
		logger.info("第二步：插入红包");

		// 问卷一档  188红包
		if(188 == s.intValue()){
			//添加注册人活动礼品信息
			ActivitieGiftDTO activitieGiftDTO = new ActivitieGiftDTO();
			activitieGiftDTO.setaType("01");
			activitieGiftDTO.setaStatus("01");//02打开红包，01未打开，03失效
			activitieGiftDTO.setaSource("03");//调查送红包
			activitieGiftDTO.setaAmount(s);
			activitieGiftDTO.setFaUserId(userId);
			//调查问卷
			activitieGiftDTO.setActiviesCode(Constants.ACTIVITIES_CODE_DCWJ);
			activitieGiftDTO.setCreateBy(userId==null?Constants.PLATFORM_ADMIN_NAME:userId.toString());
			activitieGiftDTO.setUpdateBy(userId==null?Constants.PLATFORM_ADMIN_NAME:userId.toString());
			activitieGiftDaoImpl.insertActivitieGift(activitieGiftDTO);

			logger.info("第三步：更新账户及明细");
			//更新注册人用户信息
			AccountCorpDTO accountDto =  accountDao.getFaAccountByUserId(userId);

			accountDto.setAccountBalance(accountDto.getAccountBalance().add(s));
			accountDto.setAllAccount(accountDto.getAllAccount().add(s));
			accountDto.setAccountBalanceSleep(accountDto.getAccountBalanceSleep().add(s));
			accountDto.setAccountBalanceActivity(accountDto.getAccountBalanceActivity());
			accountDto.setId(accountId);
			accountDto.setUpdateBy(userId.toString());
			accountDao.updateAccountBalanceActivity(accountDto);

			//添加注册人账户明细
			AccountDetailDTO dto = new AccountDetailDTO();
			dto.setAccountId(accountId);
			dto.setAmount(s);
			dto.setUserId(userId);
			dto.setRemark("调查问卷");
			dto.setAccountType(Constants.P_ACCOUNT_DETAIL_TYPE_INPUT);
			dto.setOperateType(Constants.P_ACCOUNT_OPERATE_ACTIVITY);
			dto.setOperateStatus(Constants.P_ACCOUNT_OPERATE_STATUS_SUCCESS);
			dto.setCreateBy(userId.toString());
			dto.setUpdateBy(userId.toString());
			dto.setActivitieGiftId(activitieGiftDTO.getId());
			accountDao.addUserAccountDetail(dto);
			return ;
		}

		//添加注册人活动礼品信息
		ActivitieGiftDTO activitieGiftDTO = new ActivitieGiftDTO();
		activitieGiftDTO.setaType("01");
		activitieGiftDTO.setaStatus("02");//02打开红包，01未打开，03失效
		activitieGiftDTO.setaSource("03");//调查送红包
		activitieGiftDTO.setaAmount(s);
		activitieGiftDTO.setFaUserId(userId);
		//调查问卷
		activitieGiftDTO.setActiviesCode(Constants.ACTIVITIES_CODE_DCWJ);
		activitieGiftDTO.setCreateBy(Constants.PLATFORM_ADMIN_NAME);
		activitieGiftDTO.setUpdateBy(Constants.PLATFORM_ADMIN_NAME);
		activitieGiftDaoImpl.insertActivitieGift(activitieGiftDTO);

		if(500>s.intValue()){//小于500则充值，等于500则充话费不进账户
			logger.info("第三步：更新账户及明细");
			//更新注册人用户信息
			AccountCorpDTO accountDto =  accountDao.getFaAccountByUserId(userId);
			accountDto.setAccountBalance(accountDto.getAccountBalance().add(s));
			accountDto.setAllAccount(accountDto.getAllAccount().add(s));
			accountDto.setAccountBalanceActivity(accountDto.getAccountBalanceActivity().add(s));
			accountDto.setId(accountId);
			accountDto.setUpdateBy(userId.toString());
			accountDao.updateAccountBalanceActivity(accountDto);
			//添加注册人账户明细
			AccountDetailDTO dto = new AccountDetailDTO();
			dto.setAccountId(accountId);
			dto.setAmount(s);
			dto.setUserId(userId);
			dto.setRemark("调查问卷");
			dto.setAccountType(Constants.P_ACCOUNT_DETAIL_TYPE_INPUT);
			dto.setOperateType(Constants.P_ACCOUNT_OPERATE_ACTIVITY);
			dto.setOperateStatus(Constants.P_ACCOUNT_OPERATE_STATUS_SUCCESS);
			dto.setCreateBy(userId.toString());
			dto.setUpdateBy(userId.toString());
			dto.setActivitieGiftId(activitieGiftDTO.getId());
			accountDao.addUserAccountDetail(dto);
		}

	}

	/**
	 * 调查问卷-初始逻辑
	 * @param userId
	 * @param sessionId
	 * @param accountId
	 * @param s
	 * @throws SQLException
	 */
	public void updateAccountAndAnswerBAK(String userId,String sessionId,Integer accountId, BigDecimal s) throws SQLException {
		logger.info("第一步：更新答案表");
		ActivitesAnswerDTO answerDto = new ActivitesAnswerDTO();
		answerDto.setuId(userId);
		answerDto.setSessionId(sessionId);
		answerDao.updateAnswerBySessionId(answerDto);
		logger.info("第二步：插入红包");

		//添加注册人活动礼品信息
		ActivitieGiftDTO activitieGiftDTO = new ActivitieGiftDTO();
		activitieGiftDTO.setaType("01");
		activitieGiftDTO.setaStatus("02");//02打开红包，01未打开，03失效
		activitieGiftDTO.setaSource("03");//调查送红包
		activitieGiftDTO.setaAmount(s);
		activitieGiftDTO.setFaUserId(userId);
		//调查问卷
		activitieGiftDTO.setActiviesCode(Constants.ACTIVITIES_CODE_DCWJ);
		activitieGiftDTO.setCreateBy(Constants.PLATFORM_ADMIN_NAME);
		activitieGiftDTO.setUpdateBy(Constants.PLATFORM_ADMIN_NAME);
		activitieGiftDaoImpl.insertActivitieGift(activitieGiftDTO);
		if(500>s.intValue()){//小于500则充值，等于500则充话费不进账户
			logger.info("第三步：更新账户及明细");
			//更新注册人用户信息
			AccountCorpDTO accountDto =  accountDao.getFaAccountByUserId(userId);
			if(accountDto==null||accountDto.getId()==null){
				accountDto =  new AccountCorpDTO();
				accountDto.setAccountBalance(s);
				accountDto.setAllAccount(s);
				accountDto.setAccountBalanceActivity(s);
				accountDto.setAccountBalanceSleep(new BigDecimal(0));
			}else{
				accountDto.setAccountBalance(accountDto.getAccountBalance().add(s));
				accountDto.setAllAccount(accountDto.getAllAccount().add(s));
				accountDto.setAccountBalanceActivity(accountDto.getAccountBalanceActivity().add(s));
			}
			accountDto.setId(accountId);
			accountDto.setUpdateBy(Constants.PLATFORM_ADMIN_NAME);
			accountDao.updateAccountBalanceActivity(accountDto);
			//添加注册人账户明细
			AccountDetailDTO dto = new AccountDetailDTO();
			dto.setAccountId(accountId);
			dto.setAmount(s);
			dto.setUserId(userId);
			dto.setRemark("调查问卷");
			dto.setAccountType(Constants.P_ACCOUNT_DETAIL_TYPE_INPUT);
			dto.setOperateType(Constants.P_ACCOUNT_OPERATE_ACTIVITY);
			dto.setOperateStatus(Constants.P_ACCOUNT_OPERATE_STATUS_SUCCESS);
			dto.setCreateBy(Constants.PLATFORM_ADMIN_NAME);
			dto.setUpdateBy(Constants.PLATFORM_ADMIN_NAME);
			dto.setActivitieGiftId(activitieGiftDTO.getId());
			accountDao.addUserAccountDetail(dto);
		}

	}
	@Override
	public int searchCountOneWeek(Map<String, Date> p) {
		return answerDao.searchCountOneWeek(p);
	}



	@Override
	public List<ActivitesMoneyDTO> searchAnswerResultTop(Integer top){
		return answerDao.searchAnswerResultTop(top);
	}

	@Override
	public Integer searchAnswerRanking(Integer answer) {

		return answerDao.searchAnswerRanking(answer);
	}

	@Override
	public Integer searchMoneyCount() {

		return answerDao.searchMoneyCount();
	}
	
	@Override
	public ActivitesMoneyDTO getMoneyScoreAndAnswerByOpenId(String unionid){
		ActivitesAnswerDTO queryDto = new ActivitesAnswerDTO();
		queryDto.setSessionId(unionid);
		queryDto.setActiviesCode(Constants.ACTIVITIES_CODE_FCZS);
		List<ActivitesAnswerDTO> list = answerDao.searchAnswerByParas(queryDto);
		if(list==null||list.isEmpty()){
			logger.info("FCZS activies is not found this openId...");
			return null;
		}
		ActivitesAnswerDTO joinDto = list.get(0);
		logger.info(" This openId has join FCZS activites,now return join info...");
		//分数结果
		ActivitesMoneyDTO moneyDto = new ActivitesMoneyDTO();
		Integer ranking = getRanking(Integer.valueOf(joinDto.getAnswer()));
		
		//
		moneyDto.setAnswer(joinDto.getAnswer());
		moneyDto.setScore(joinDto.getScore());
		moneyDto.setRanking(ranking);
		return moneyDto;
	}

	@Override
	public ActivitesMoneyDTO getMoneyScoreAndAnswer(String qajson) {


		Map<String,Object> returnMap  = getAnswerByResult(qajson);
		//财富指数
		Integer allAnswer = (Integer)returnMap.get("allAnswer");
		//财富钱数
		Integer allScore = (Integer)returnMap.get("allScore");
		//微信opernID
		String unionid = (String)SessionUtil.getSession().getAttribute(Constants.ACTIVITIES_CODE_FCZS_SESSION_UNIONID);
		logger.info(" api getResult openId is "+unionid);
//		if(StringUtil.isNullOrEmptyStr(openId)){
//			openId = "oW-4Ps2aPBGpct_w_Pznp78ALNVM";
//		}

		ActivitesAnswerDTO insertAnwerDTO = new ActivitesAnswerDTO();
		insertAnwerDTO.setActiviesCode(Constants.ACTIVITIES_CODE_FCZS);
		insertAnwerDTO.setAnswer(allAnswer.toString());
		insertAnwerDTO.setScore(allScore);
		insertAnwerDTO.setSessionId(unionid);//unionid
		insertAnwerDTO.setqId(0);
		insertAnwerDTO.setCreateBy("platForm");
		insertAnwerDTO.setUpdateBy("platForm");
		answerDao.insertAnswer(insertAnwerDTO);
		//分数结果
		ActivitesMoneyDTO moneyDto = new ActivitesMoneyDTO();
		
		Integer ranking = getRanking(allAnswer);
	
		moneyDto.setAnswer(allAnswer.toString());
		moneyDto.setScore(allScore);
		moneyDto.setRanking(ranking);
		logger.info("ranking is "+ranking);
		return moneyDto;
	};



	/**
	 * 将提交的答案排序整理为提交大难list
	 * @return
	 */
	private List<ActiviesMoneyAnswerVo> getAnswerList(String qajson){
		//		qajson = "{'2':'3','8':'2','9':'1','11':'2','13':'3','14':'3','15':'1','16':'4','17':'3','18':'4','19':'-1'}";
		JSONObject json = JSON.parseObject(qajson);
		Set<String> keySet = json.keySet();
		Iterator<String> keyIterator = keySet.iterator();
		List<ActiviesMoneyAnswerVo> answerList = new ArrayList<ActiviesMoneyAnswerVo>();
		while(keyIterator.hasNext()){
			ActiviesMoneyAnswerVo answerResult = new ActiviesMoneyAnswerVo();
			String key = keyIterator.next();
			String values = json.get(key).toString();
			answerResult.setQ(Integer.valueOf(key));
			answerResult.setA(Integer.valueOf(values));
			answerList.add(answerResult);
		};
		ActiviesMoneyAnswerVo answerSort=new ActiviesMoneyAnswerVo();
		Collections.sort(answerList, answerSort);


		return answerList;
	}
	
	
	/**
	 * 排名百分比
	 * @param answer
	 * @return
	 */
	private Integer getRanking(Integer answer){
		Integer count = searchMoneyCount();
		Integer rankingCount = searchAnswerRanking(answer);
		if(1==count){
			return 100;
		}
		if(0==rankingCount){
			rankingCount = 1;
		}
		count = count-1;
		Double r = Double.valueOf(rankingCount)/Double.valueOf(count);
		logger.info("activity join all num is "+count+";top me is "+rankingCount);
		Integer ranking = Integer.valueOf(String.valueOf(Math.round(r*100)));
		return ranking;
	}
	
	/**
	 * 获取财富指数
	 * @return
	 */
	private Map<String,Object> getAnswerByResult(String qajson){
		List<ActiviesMoneyAnswerVo> answerList = getAnswerList(qajson);
		Map<String,Object> returnMap = new HashMap<String,Object>();
		//		List<Integer>  allScoreList = new ArrayList<Integer>();
		Integer allAnswer =0;
		Integer allScore = 0;
		//8.9.10题的正确系数
		double ff=0.25;
		//朋友个数系数
		Integer friendNum = 10;
		//最后一题系数
		Integer last = 1;
		//朋友个数
		Integer a13 = answerList.get(4).getA();//第13题
		//专业题
		Integer a16 = answerList.get(7).getA();//第16题
		Integer a17 = answerList.get(8).getA();//第17题
		Integer a18 = answerList.get(9).getA();//第18题

		for(ActiviesMoneyAnswerVo vo:answerList){
			Integer q = vo.getQ();
			Integer a = vo.getA();
			Integer tempA = 0;
			//19题加分题规则
			if("19".equals(q.toString())){
				//if16~18题选对了，19题也选对了才加1分
				if(a.equals(-1)&&a16.equals(4)&&a17.equals(4)&&a18.equals(4)){//8、9、10题全选中且11题也选中
					allAnswer = allAnswer+1;
					logger.info("question:"+q+"--answer:1");
					last =  RandomUtils.getRandomNumUtils(11, 13);
					continue;
				}
				last =  RandomUtils.getRandomNumUtils(9, 11);
				logger.info("question:"+q+"--answer:0");
				continue;
			}
			//14题与15题的关联处理
			if(q.equals(15)){
				Integer a14 = answerList.get(5).getA();//第14题
				//				 上题A   A   9-10    B  8-9    C  6-8   D  1-5
				//			       上题B   A   6-8     B  9-10   C  8-9   D  1-5
				//			       上题C   A   6-8     B  8-9    C  9-10  D  1-5
				//			       上题D   A   1-5     B  6-8    C  8-9   D  9-10
				if(a14.equals(1)){//14题选择D
					if(a.equals(1)){
						a=4;
					}else if(a.equals(2)){
						a=3;
					}else if(a.equals(3)){
						a=2;
					}else if(a.equals(4)){
						a=1;
					}
				}else if(a14.equals(2)){//14题选择C
					if(a.equals(1)){
						a=1;
					}else if(a.equals(2)){
						a=4;
					}else if(a.equals(3)){
						a=3;
					}else if(a.equals(4)){
						a=2;
					}
				}else if(a14.equals(3)){//14题选择B
					if(a.equals(1)){
						a=1;
					}else if(a.equals(2)){
						a=3;
					}else if(a.equals(3)){
						a=4;
					}else if(a.equals(4)){
						a=2;
					}
				}
			}

			//常规得分
			if(a.equals(1)){//1~5分
				tempA = RandomUtils.getRandomNumUtils(1, 6);
				//				allScoreList.add(tempA);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*800;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
			if(a.equals(2)){//6~8分
				tempA = RandomUtils.getRandomNumUtils(6, 9);
				//				allScoreList.add(tempA);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*1000;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
			if(a.equals(3)){//8~9分
				tempA = RandomUtils.getRandomNumUtils(8, 10);
				//				allScoreList.add(tempA);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*3000;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
			if(a.equals(4)){//9~10分
				tempA = RandomUtils.getRandomNumUtils(9, 11);
				//				allScoreList.add(tempA);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*10000;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
		}
		/*****************计算财富数**********************/
		//最后一题系数
		
		double ld = last.doubleValue()/(double)10;
		//朋友个数系数
		if(a13.equals(1)){//答案A
			friendNum = 10;
		}else if(a13.equals(2)){//答案B
			friendNum = 15;
		}else if(a13.equals(3)){//答案C
			friendNum = 25;
		}else if(a13.equals(4)){//答案D
			friendNum = 30;
		}
		//计算8.9.10题的正确加成系数，对一个加25%
		if(a16.equals(4)){
			ff=ff+0.25;
		}if(a17.equals(4)){
			ff=ff+0.25;
		}if(a18.equals(4)){
			ff=ff+0.25;
		}

		//		logger.info(allScore+"=="+ff+"=="+ld);
		logger.info("last quesiton coefficient is "+ld);
		logger.info("last quesiton coefficient is "+ld);
		logger.info("all answer is "+allAnswer);
		returnMap.put("allAnswer",  allAnswer);
		returnMap.put("allScore", new Double(allScore*ff*ld*friendNum).intValue());
		return returnMap;
	}

}
